//
//  SureReserveViewController.m
//  Manager
//
//  Created by 彭凯敏 on 15/8/17.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "SureReserveViewController.h"
#import "AlreadySignViewController.h"
#import "SearchViewController.h"
#import "SearchCell.h"
@interface SureReserveViewController ()<searchDelegate>
{
    NSArray *tfArray;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *idTF;
@property (weak, nonatomic) IBOutlet UITextField *roomTF;
@property (weak, nonatomic) IBOutlet UILabel *roomStatus;

@property (weak, nonatomic) IBOutlet UITextField *personNumTF;
@property (weak, nonatomic) IBOutlet UITextField *depositTF;
@property (weak, nonatomic) IBOutlet UITextField *priceTF;

@property (weak, nonatomic) IBOutlet UITextField *moneyTF;
@property (weak, nonatomic) IBOutlet UITextView *remarkText;

- (IBAction)clickSure:(UIButton *)sender;


//timeView
- (IBAction)clickTimeView:(UITapGestureRecognizer *)sender;
@property (weak, nonatomic) IBOutlet UIView *startTimeView;
@property (weak, nonatomic) IBOutlet UIView *endtimeView;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;

@property (strong, nonatomic) IBOutlet UIView *pickView;
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
- (IBAction)dateChanged:(UIDatePicker *)sender;
- (IBAction)clickPickSure:(UIButton *)sender;
@property (strong, nonatomic) UIView *currentView;



//search
@property (strong, nonatomic) UITableView *searchTableView;
@property (strong, nonatomic) NSMutableArray *searchDataArray;
@property (strong, nonatomic) NSMutableArray *roomArray;


@end

@implementation SureReserveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     [self baseCtlSetTitle:@"用户确认订房"];
    _roomArray = [[NSMutableArray alloc]initWithObjects:@"", nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestSuccess:) name:CMD_ViewRoom_ReserveRoomReq object:nil];

    [_contentView setSizeWidth:ScreenWidth];
    
    _scrollView.contentSize = CGSizeMake(ScreenWidth, _contentView.sizeHeight);
    
    
    [_scrollView addSubview:_contentView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewTap:)];
    [_scrollView addGestureRecognizer:tap];
    
    [self resetUI];
    
    tfArray = @[_personNumTF,_priceTF,_nameTF,_phoneTF,_idTF,_moneyTF,_remarkText];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    [self clickPickSure:nil];
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    UIView *textField;
    for (NSInteger i = 0; i<tfArray.count; i++) {
        if ([tfArray[i] isFirstResponder]) {
            textField = tfArray[i];
        }
    }
    
    if (!textField) {
        return;
    }
    
    [UIViewCategory offsetText:textField Height:height Super:_scrollView];
    
    
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{

    
}
- (void)resetUI
{
    _startTimeLabel.tag = 101;
    _endTimeLabel.tag = 101;
    
    if (_orderInfo.viewRooms) {
        
        RoomInfo *info = _orderInfo.viewRooms[0];
        _roomTF.text = info.name;
        _roomStatus.text = [UIViewCategory roomStatusWith:info];
         _priceTF.text = [NSString stringWithFormat:@"%d",(int)info.price];
        [_roomArray replaceObjectAtIndex:0 withObject:info];
        
    }
    _personNumTF.text = @"1";
    _nameTF.text = _orderInfo.name;
    _phoneTF.text = _orderInfo.phone;
    
    _idTF.text = @"";

    
}

#pragma mark - request

- (void)RoomSearchReqWithtext:(NSString *)text
{
    RoomSearchReqBuilder *builder = [[RoomSearchReqBuilder alloc]init];
    RoomFilterBuilder *filter = [[RoomFilterBuilder alloc]init];
    [filter setName:text];
    
    [builder setRoomFilter:filter.build];
    
    [[ViewRoomLogic shareInstance]roomSearchReqWithBuild:builder.build];
    
}
- (void)ReserveRoomReq
{
    ReserveRoomReqBuilder *builder = [[ReserveRoomReqBuilder alloc]init];
    [builder setIsReserve:YES];
    [builder setViewOrderId:_orderInfo.id];

    SignInfoBuilder *infoBuilder = [[SignInfoBuilder alloc]init];
    
    
    RoomInfo *room = _roomArray[0];
    
    [infoBuilder setRoomId:room.roomId];
    
    [infoBuilder setName:_nameTF.text];
    [infoBuilder setPhone:_phoneTF.text];
    [infoBuilder setDeposit:[_depositTF.text longLongValue]];
    
    [infoBuilder setPersonNum:[_personNumTF.text intValue]];
    [infoBuilder setFinalPrice:[_priceTF.text intValue]];
    [infoBuilder setIdNumber:_idTF.text];
    [infoBuilder setSignStewardId:[[ UserLogic shareInstance]getUserId]];
    
    
    [infoBuilder setContractStartTime:[[KMGetDate timespFromTimeStr:_startTimeLabel.text andFormatter:@"yyyy/MM/dd"] longLongValue]*1000];
    [infoBuilder setContractEndTime:[[KMGetDate timespFromTimeStr:_endTimeLabel.text andFormatter:@"yyyy/MM/dd"] longLongValue]*1000];
    
    [infoBuilder setHasAmount:[_moneyTF.text longLongValue]];
    [infoBuilder setHasAmountRemark:_remarkText.text];
    
    
    
    [builder setSignInfo: infoBuilder.build];
    
    [[ViewRoomLogic shareInstance]reserveRoomReqWithBuild:builder.build];
}

- (void)requestSuccess:(NSNotification *)noti
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([noti.name isEqualToString:CMD_ViewRoom_ReserveRoomReq]) {
            
            HUDRemove;
            
            if ([noti.object isKindOfClass:[ErrorModel class]])
            {
                ErrorModel *model = noti.object;
                [UIViewCategory FailShowWith:model];
                
                return ;
            }
            SuccessShow(@"提交成功！");
            
            [self.navigationController pushViewController:[[AlreadySignViewController alloc] init] animated:YES];
            
            NSArray *array = self.navigationController.viewControllers;
            self.navigationController.viewControllers = @[array[0],array[3]];
            
        }

        
    });
}

#pragma mark - event
- (void)scrollViewTap:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
    
    if (_scrollView.contentOffset.y > _contentView.sizeHeight - _scrollView.sizeHeight) {
        
        [UIView animateWithDuration:0.25 animations:^{
            [self .scrollView setContentOffset:CGPointMake(0, _contentView.sizeHeight - _scrollView.sizeHeight)];
        }];
        
    }
}
- (IBAction)clickSure:(UIButton *)sender {

    if ([_roomTF.text isEqualToString:@""]||[_personNumTF.text isEqualToString:@""]||[_priceTF.text isEqualToString:@""]||[_depositTF.text isEqualToString:@""]||[_startTimeLabel.text isEqualToString:@""]||[_endTimeLabel.text isEqualToString:@""]) {
        FailedShow(@"请完善合同信息");
        return;
    }
    if ([_nameTF.text isEqualToString:@""]||[_phoneTF.text isEqualToString:@""]||[_idTF.text isEqualToString:@""]) {
        FailedShow(@"请完善租客信息");
        return;
    }
    if ([KMCheckTel checkTel:[_phoneTF.text stringByReplacingOccurrencesOfString:@" " withString:@""]] == NO) {
        FailedShow(@"请填写正确的手机号");
        return;
    }
    
    KMAlertView *alert = [[KMAlertView alloc]initWithTitle:@"确认订房" message:@"请确认所填写的信息完整无误，确定好该房源将下架" cancelButtonTitle:@"取消" clickButton:^(NSInteger index) {
        
        if (index == 1) {
            
            HUDShow(nil);
            [self ReserveRoomReq];
        }
        
        
    } otherButtonTitles:@"确定"];
    
    [alert show];
    
}


#pragma mark - UIScrollViewDelegate


- (void)searchSelectRoom:(RoomInfo *)info
{
    _roomTF.text = info.name;
    [_roomArray replaceObjectAtIndex:0 withObject:info];
    _roomStatus.text = [UIViewCategory roomStatusWith:info];
    
}

- (void)searchNoRoom
{
    _roomTF.text = @"";
    _roomStatus.text = @"";
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{

    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    if (textField == _roomTF) {
        
        SearchViewController *search = [[SearchViewController alloc]init];
        
        search.searchStr = textField.text;
        search.delegate = self;
        
        [self.navigationController pushViewController:search animated:YES];
        
    }
    return  YES;
    
    
}



#pragma mark - time
- (IBAction)clickTimeView:(UITapGestureRecognizer *)sender {
    
    _currentView = sender.view;
    
    [self.view endEditing:YES];
    
    [UIViewCategory offsetText:_currentView Height:IS320?225:280 Super:_scrollView];
    
    if (_currentView == _startTimeView) {
        RoomInfo *info =  _roomArray[0];
        if (info.contractEndTime>0) {
            _datePicker.minimumDate = [NSDate dateWithTimeIntervalSince1970:info.contractEndTime/1000];
        }
        else
        {
            _datePicker.minimumDate = [NSDate date];
            
        }
        if (![_startTimeLabel.text isEqualToString:@""]) {
            [_datePicker setDate:[KMGetDate dateFromTimeStr:_startTimeLabel.text andFormatter:@"yyyy/MM/dd"] animated:YES];
        }
    }
    else if (_currentView == _endtimeView)
    {
        if ([_startTimeLabel.text isEqualToString:@""]) {
            FailedShow(@"请先选择起租时间");
            return;
        }
        _datePicker.minimumDate = [KMGetDate dateFromTimeStr:_startTimeLabel.text andFormatter:@"yyyy/MM/dd"];
        if (![_endTimeLabel.text isEqualToString:@""]) {
            [_datePicker setDate:[KMGetDate dateFromTimeStr:_endTimeLabel.text andFormatter:@"yyyy/MM/dd"] animated:YES];
        }
    }
    
    if (_pickView.originY == ScreenHeight-64-_pickView.sizeHeight) {
        return;
    }

    

    [_pickView setOriginY:ScreenHeight-64];
    [_pickView setSizeWidth:ScreenWidth];
    [_pickView setSizeHeight:IS320?225:280];
    [self.view addSubview:_pickView];
    [UIView animateWithDuration:0.3 animations:^{
        
        [_pickView setOriginY:ScreenHeight-64-_pickView.sizeHeight];
    }];
}
- (IBAction)dateChanged:(UIDatePicker *)sender {
    
    
    NSString *timeStr = [self stringFromDate:sender.date];
    if (_currentView == _startTimeView) {
        _startTimeLabel.text = timeStr;
    }
    else if (_currentView == _endtimeView)
    {
        _endTimeLabel.text = timeStr;
    }
    
}

- (IBAction)clickPickSure:(UIButton *)sender {
    [self dateChanged:_datePicker];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [_pickView setOriginY:ScreenHeight-64];
    }];
    
}
- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}


@end
